package com.assets.Repairs;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.assets.Adapter.Addrepairs_Adapter1;
import com.assets.Check.newTanWanCheck.BaseActivity1;
import com.assets.bean.AddRepairs_bean1;
import com.assets.newNHF.util.LogUtils;
import com.assets.util.MyOkHttp;
import com.assets.util.MyRFIDHandle;
import com.assets.util.RFIDClientUtil;
import com.assets.util.Since_case;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.assets.Ip_set.Url;
import com.assets.R;
import com.assets.Scan.qrcode.util.Constant;
import com.assets.Scan.zxing.activity.CaptureActivity;
import com.assets.CanniBalize.Shift_site;
import com.hb.dialog.myDialog.MyAlertInputDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Response;

/**
 * Created by Administrator on 2019/5/9.
 */

public class Add_Repairs extends BaseActivity1 {
    private TextView title_text, site_tv;//标题，部门，报修人，临时存放
    private LinearLayout site;//部门，报修人，临时存放
    private ImageView fh;
    private String url = "http://" + Url.IP + "/api/repairsAddInspect";
    private String upload_url = "http://" + Url.IP + "/api/repairsAdd";
    private List<String> numbers = new ArrayList<>();//编号集合
    private List<String> remarks = new ArrayList<>();//集合s
    private List<AddRepairs_bean1> data = new ArrayList<>();
    private List<String> lv_data = new ArrayList<>();//判断是否重复
    private ListView listView;
    private String site_id = "";
    private TextView et;
    private Button scan_img, uploading, btn_rfid;
    private EditText et_num;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.add_repairs);
        inview();
    }

    private void inview() {
        et_num = (EditText) findViewById(R.id.et_num);
        et_num.setFocusableInTouchMode(true);
        et_num.requestFocus();
        uploading = (Button) findViewById(R.id.upload);
        listView = (ListView) findViewById(R.id.fragment2_list);
        scan_img = (Button) findViewById(R.id.scan_img);
        et = (EditText) findViewById(R.id.remark);
        site_tv = (TextView) findViewById(R.id.site_tv);
        site = (LinearLayout) findViewById(R.id.site);
        title_text = (TextView) findViewById(R.id.title_text);
        title_text.setText("新建报修单");
        fh = (ImageView) findViewById(R.id.fh);
        fh.setOnClickListener(v -> finish());
        et_num.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable S) {
                et_num.selectAll();
                for (int i = 0; i < data.size(); i++) {
                    if (S.equals(data.get(i).getCode_number())) {
                        showToast("该资产已存在列表");
                        return;
                    }
                }
                if (!et_num.getText().toString().trim().equals("") && et_num.length() > 9) {
                    if (!lv_data.contains(et_num.getText().toString().trim())) {
                        scanAsset(et_num.getText().toString().trim());
                    } else showToast("该资产已存在列表");
                } else {
                    showToast("错误的格式");
                }
            }
        });
        //存放位置
        site.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Add_Repairs.this, Shift_site.class);
                startActivityForResult(intent, 3);
            }
        });
        scan_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startQrCode();
            }
        });
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, final int i, long id) {
                new AlertView(" 提示！", "是否删除", "取消", new String[]{"确定"}, null, Add_Repairs.this, AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        //取消：position=-1,确定 position=0
                        if (position == 0) {
                            for (int j = 0; j < lv_data.size(); j++) {
                                if (lv_data.get(j).equals(data.get(i).getCode_number())) {
                                    lv_data.remove(j);
                                }
                            }
                            data.remove(i);
                            Addrepairs_Adapter1 adapter_item = new Addrepairs_Adapter1(Add_Repairs.this, R.layout.addrepairs_item, data, "1");
                            listView.setAdapter(adapter_item);
                        }
                    }
                }).setCancelable(true).show();
                return true;
            }
        });
        listView.setOnItemClickListener((parent, view, i, id) -> {
            final MyAlertInputDialog myAlertInputDialog = new MyAlertInputDialog(Add_Repairs.this).builder()
                    .setTitle("提示！！！")
                    .setEditText("请输入故障备注");
            myAlertInputDialog.setPositiveButton("确认", v -> {
                data.get(i).setRemark(myAlertInputDialog.getResult());
                myAlertInputDialog.dismiss();
            }).setNegativeButton("取消", v -> myAlertInputDialog.dismiss());
            myAlertInputDialog.show();
        });
        uploading.setOnClickListener(v -> {
            if (site_id.equals("")) {
                showToast("请选择存放位置");
                return;
            }
            if (data.size() > 0) {
                new AlertView(" 提示！", "是否上传数据", "取消", new String[]{"确定"}, null, Add_Repairs.this, AlertView.Style.Alert, new OnItemClickListener() {
                    @Override
                    public void onItemClick(Object o, int position) {
                        //取消：position=-1,确定 position=0
                        if (position == 0) {
                            numbers.clear();
                            remarks.clear();
                            for (int i = 0; i < data.size(); i++) {
                                numbers.add(data.get(i).getCode_number());
                                remarks.add(data.get(i).getRemark());
                            }
                            submitData();
                        }
                    }
                }).setCancelable(true).show();
            } else {
                showToast("请扫码添加需保修的资产");
            }
        });
        btn_rfid = findViewById(R.id.btn_rfid);
        btn_rfid.setOnClickListener(v -> {
            String rfidTitle = btn_rfid.getText().toString();
            if (rfidTitle.equals("开始读取")) {
                rfidClientUtil.read();
            } else {
                rfidClientUtil.stop();
            }
        });
        initRFID();
    }

    private RFIDClientUtil rfidClientUtil;
    private Map<String, String> map = new HashMap<>();

    private void initRFID() {
        MyRFIDHandle myRFIDHandle = new MyRFIDHandle();
        myRFIDHandle.post(() -> {
            rfidClientUtil = new RFIDClientUtil(epc -> {
                if (map.containsKey(epc)) {
                    return;
                }
                map.put(epc, "");
                readAsset(epc);
            });
            rfidClientUtil.setRequestStop(() -> runOnUiThread(() -> {
                btn_rfid.setText("开始读取");
            }));
            rfidClientUtil.setRequestRead(() -> runOnUiThread(() -> {
                btn_rfid.setText("停止读取");
            }));
            getLifecycle().addObserver(myRFIDHandle);
            getLifecycle().addObserver(rfidClientUtil);
        });
    }


    private void submitData() {
        Map<String, String> map = new HashMap<>();
        map.put("assetNumbers", numbers.toString());
        map.put("place", site_id);
        map.put("operator", Since_case.getInstance().getUserId());
        map.put("userId", Since_case.getInstance().getUserId());
        map.put("fremark", et.getText().toString());
        map.put("details", remarks.toString());
        MyOkHttp.getInstance().post(upload_url, map, new MyOkHttp.requestMessage() {
            @Override
            public void requestFail() {
                LogUtils.d("error");
            }

            @Override
            public void requestComplete() {
            }

            @Override
            public void requestSuccess(Response response) throws IOException {
                final String responseData = response.body().string();
                LogUtils.d(responseData);
                //回调方法的使用与get异步请求相同
                try {
                    JSONObject json = new JSONObject(responseData);
                    if (json.getString("state").equals("1")) {
                        data.clear();
                        lv_data.clear();
                        Addrepairs_Adapter1 adapter_item = new Addrepairs_Adapter1(Add_Repairs.this, R.layout.addrepairs_item, data, "1");
                        runOnUiThread(() -> {
                            listView.setAdapter(adapter_item);
                            showToast("提交成功");
                            finish();
                        });
                    }
                    if (json.getString("state").equals("0")) {
                        showToast("提交失败");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private void scanAsset(final String scanResult) {
        Map<String, String> map = new HashMap<>();
        map.put("assetNumber", scanResult);
        map.put("userId", Since_case.getInstance().getUserId());
        map.put("remark", "");
        post(url, map, responseData -> {
            handleAssetData(responseData);
        });
    }

    private void readAsset(final String epc) {
        Map<String, String> map = new HashMap<>();
        map.put("rfid", epc);
        map.put("userId", Since_case.getInstance().getUserId());
        map.put("remark", "");
        post(url, map, responseData -> {
            handleAssetData(responseData);
        }, () -> {
            this.map.remove(epc);
        });
    }

    private void handleAssetData(String responseData) {
        LogUtils.d(responseData);
        //回调方法的使用与get异步请求相同
        try {
            JSONObject json = new JSONObject(responseData);
            if (json.getString("state").equals("0")) {
                showToast("失败");
            }
            if (json.getString("state").equals("1")) {
                JSONObject jsonObject = json.getJSONObject("asset");
                String assetName = jsonObject.getString("assetName");
                String deptId = jsonObject.getString("deptId");
                String assetNumber = jsonObject.getString("assetNumber");
                String userId = jsonObject.getString("userId");
                String model = jsonObject.getString("model");
                String type = jsonObject.getString("type");
                String remark = jsonObject.getString("remark");
                if (lv_data.contains(assetNumber)) {
                    showToast("该资产已存在列表");
                    return;
                }
                lv_data.add(assetNumber);
                String image = jsonObject.getString("image");
                if (!TextUtils.isEmpty(image)) {
                    image = "http://" + Url.IP + image;
                }
                data.add(new AddRepairs_bean1(image, assetName, deptId, assetNumber, userId, model, type, remark, "类别", ""));
                Addrepairs_Adapter1 adapter_item = new Addrepairs_Adapter1(Add_Repairs.this, R.layout.addrepairs_item, data, "1");
                runOnUiThread(() -> {
                    listView.setAdapter(adapter_item);
                });
            }
            if (json.getString("state").equals("2")) {
                showToast("不存在此资产");
            }
            if (json.getString("state").equals("3")) {
                showToast("此资产已报修");
            }
            if (json.getString("state").equals("4")) {
                showToast("此资产不能报修");
            }
            if (json.getString("state").equals("5")) {
                showToast("资产不属于用户管理");
            }
            if (json.get("state").equals("6")) {
                showToast("资产不属于用户管理部门管理");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // 开始扫码
    private void startQrCode() {
        // 申请相机权限
        if (ActivityCompat.checkSelfPermission(Add_Repairs.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Add_Repairs.this, new String[]{Manifest.permission.CAMERA}, Constant.REQ_PERM_CAMERA);
            return;
        }
        // 申请文件读写权限（部分朋友遇到相册选图需要读写权限的情况，这里一并写一下）
        if (ActivityCompat.checkSelfPermission(Add_Repairs.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 申请权限
            ActivityCompat.requestPermissions(Add_Repairs.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, Constant.REQ_PERM_EXTERNAL_STORAGE);
            return;
        }
        // 二维码扫码
        Intent intent = new Intent(Add_Repairs.this, CaptureActivity.class);
        startActivityForResult(intent, Constant.REQ_QR_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent datas) {
        super.onActivityResult(requestCode, resultCode, datas);
        if (requestCode == 3 && resultCode == 3) {
            String name = datas.getExtras().getString("site_name");
            site_id = datas.getExtras().getString("site_id");
            site_tv.setText(name);
            LogUtils.d("临时存放位置id" + site_id + name);
        }
        //扫描结果回调
        if (requestCode == Constant.REQ_QR_CODE && resultCode == RESULT_OK) {
            Bundle bundle = datas.getExtras();
            final String scanResult = bundle.getString(Constant.INTENT_EXTRA_KEY_QR_SCAN);
            //将扫描出的信息显示出来
            if (!lv_data.contains(scanResult)) {
                scanAsset(scanResult);
            } else showToast("该资产已存在列表");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case Constant.REQ_PERM_CAMERA:
                // 摄像头权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    showToast("请至权限中心打开本应用的相机访问权限");
                }
                break;
            case Constant.REQ_PERM_EXTERNAL_STORAGE:
                // 文件读写权限申请
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 获得授权
                    startQrCode();
                } else {
                    // 被禁止授权
                    showToast("请至权限中心打开本应用的文件读写权限");
                }
                break;
        }
    }

}
